using System;
using System.Reflection;

namespace PropertyExpression.Common
{
    public static class CustomAttributeProviderExtensions
    {
        public static IOptionalResult<T> GetCustomAttribute<T>(this ICustomAttributeProvider propertyInfo)
        {
            var propertyAttributes = propertyInfo
                .GetCustomAttributes(typeof (T), true);
            switch (propertyAttributes.Length)
            {
                case 1:
                    return((T)propertyAttributes[0]).AsOptionalResult();
                case 0:
                    return OptionalResult.AsOptionalResult<T>();
                default:
                    throw new ApplicationException();
            }
        }
    }
}